//Copyright 2008 by Wes Corp for Trafficman  All rights reserved.abstract 
package org.trafficman.trafficman_main;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.Menu.Item;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Gallery.LayoutParams;

public class TrafficmanMainActivity extends ListActivity {

    private static final int ACTIVITY_CREATE = 0;
    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;
    private TrafficmanFilesNotesDbAdapter mDbHelper;
    private SQLiteDatabase db;
    private SQLiteDatabase db_files;
    private SQLiteDatabase db_servers;
    private int int_intent_active;
    private int int_selected_id;
    private String title_text;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        Window w = getWindow();
        w.requestFeature(Window.FEATURE_LEFT_ICON);

        setContentView(R.layout.files_notes_list);

        LinearLayout tmpLayout = (LinearLayout) findViewById(R.id.linearlayout_001);
        TrafficmanConstants.SCREEN_VIEWWIDTH = this.getResources().getDisplayMetrics().widthPixels;
        TrafficmanConstants.SCREEN_VIEWHEIGHT = this.getResources().getDisplayMetrics().heightPixels;
        get_Trafficman_Screen(); // set trafficman2 background

        int resID = getResources().getIdentifier(TrafficmanConstants.SCREEN_NAME, null,
                null);
        tmpLayout.setBackground(resID);

        // setup system
        TrafficmanInitialize();

        // create database for devices, trafficman files, server locations
        createTrafficmanFilesDB();

        // create list of trafficman files
        mDbHelper = new TrafficmanFilesNotesDbAdapter(this);
        mDbHelper.open();
        fillData();

        // setup title bar
        title_text = getString(R.string.trafficman_files_title);
        this.setTitle(title_text);
        w.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
                R.drawable.tm_icon);
    }

    private void createTrafficmanFilesDB() {

        // create database for trafficman files for files on device
        try {
            db_files = openDatabase(TrafficmanConstants.DATABASE_FILES, null);
        } catch (FileNotFoundException e) {
            try {
                db_files = createDatabase(TrafficmanConstants.DATABASE_FILES,
                        TrafficmanConstants.DATABASE_VERSION, 0, null);
                db_files.execSQL("create table if not exists jv_files" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, jv_title text not null, jv_selected_file_id integer, datetime_record_created text not null, datetime_record_updated text not null, jv_filename text not null);");
            } catch (FileNotFoundException e1) {
                db_files = null;
            }
        }

        // create database for trafficman files for files on sdcard
        if (TrafficmanConstants.ACTIVE_DEVICE.equals("sdcard")) {
            try {
                db_files = SQLiteDatabase.open(TrafficmanConstants.DATABASE_FILES_SDCARD,
                        null);
                if (db_files == null) {
                    db_files = SQLiteDatabase.create(
                            TrafficmanConstants.DATABASE_FILES_SDCARD,
                            TrafficmanConstants.DATABASE_VERSION, null);
                    db_files.execSQL("create table if not exists jv_files_sdcard" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, jv_title text not null, jv_selected_file_id integer, datetime_record_created text not null, datetime_record_updated text not null, jv_filename text not null);");
                }
            } catch (Exception e) {
                AlertDialog.show(this, "Trafficman2 SDCard Data Error", 1,
                        "Data Exception", "OK", false);
            }

        }

        // create database for server locations
        try {
            db_servers = openDatabase(TrafficmanConstants.DATABASE_SERVERS, null);

        } catch (FileNotFoundException e) {
            try {
                db_servers = createDatabase(TrafficmanConstants.DATABASE_SERVERS,
                        TrafficmanConstants.DATABASE_VERSION, 0, null);
                db_servers.execSQL("create table if not exists jv_servers" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, jv_server_title text not null, jv_server_url text not null, jv_server_user text not null, jv_server_pwd text not null, jv_selected_server_id integer, datetime_record_created text not null, datetime_record_updated text not null);");

            } catch (FileNotFoundException e1) {
                db_servers = null;
            }
        }

    }

    private void get_Trafficman_Screen() {
        TrafficmanScreens mScreens = new TrafficmanScreens(this);
    }

    private void fillData() {
        // Get all of the rows from the database and create the item list
        Cursor notesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(notesCursor);
        String[] from = new String[]{TrafficmanFilesNotesDbAdapter.KEY_JV_TITLE};
        int[] to = new int[]{R.id.text1};
        SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
                R.layout.files_notes_row, notesCursor, from, to);
        setListAdapter(notes);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID, R.string.tm_files_menu_insert,
                R.drawable.projects_006);
        menu.add(0, DELETE_ID, R.string.tm_files_menu_delete,
                R.drawable.projects_007);
        menu.add(0, 202, R.string.tm_files_menu_upload, R.drawable.tm_icon4);
        menu.add(0, 201, R.string.tm_files_menu_download, R.drawable.tm_icon5);
        menu.add(0, 203, R.string.tm_files_menu_servers, R.drawable.network_05);
        menu.add(0, 204, R.string.tm_files_menu_rename, R.drawable.tm_icon5);
        menu.add(0, 205, R.string.tm_files_location, R.drawable.network_05);
        menu.add(0, 206, "LocationDB Test", R.drawable.tm_icon4);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, Item item) {
        switch (item.getId()) {
            case INSERT_ID:
                createNote();
                return true;
            case DELETE_ID:
                mDbHelper.deleteNote(getListView().getSelectedItemId());
                fillData();
                return true;
            case 201:
                TrafficmanFileDownload();
                return true;
            case 203:
                TrafficmanFileServe_Notepad();
                return true;
            case 204:
                TrafficmanFilesNotepadEdit();
                return true;
            case 205:
                TrafficmanFilesLocationNotepad();
                return true;
            case 206:
                TrafficmanLocationTestingNotepad();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    private void TrafficmanLocationTestingNotepad() {
        Intent intent = new Intent(this, TrafficmanLocationTestingNotepad.class);
        startSubActivity(intent, ACTIVITY_CREATE);
        finish();
    }

    private void TrafficmanFilesLocationNotepad() {
        Intent intent = new Intent(this, TrafficmanFilesLocationNotepad.class);
        startSubActivity(intent, ACTIVITY_CREATE);
    // finish();
    }

    private void TrafficmanFilesNotepadEdit() {
        Intent intent = new Intent(this, TrafficmanFilenameNotepad.class);
        startSubActivity(intent, ACTIVITY_CREATE);
        finish();
    }

    private void TrafficmanFileServe_Notepad() {
        Intent intent = new Intent(this, TrafficmanFileServerNotepad.class);
        startSubActivity(intent, ACTIVITY_CREATE);
    // finish();
    }

    private void TrafficmanFileDownload() {
        Intent intent = new Intent(this, TrafficmanFileDownload.class);
        startSubActivity(intent, ACTIVITY_CREATE);
    // finish();
    }

    private void createNote() {
        int_intent_active = 1;
        Intent intent = new Intent(this, TrafficmanFilesNoteEdit.class);
        startSubActivity(intent, ACTIVITY_CREATE);
    }

    // Select a Trafficman File
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        int_intent_active = 1;

        set_Current_JV_file(id);
        get_Current_JV_file();
        TrafficmanInitialize();

        // TODO naming the databases
        if (TrafficmanConstants.ACTIVE_DEVICE.equals("sdcard")) {
            TrafficmanConstants.DATABASE_NAME = "/sdcard/default" + TrafficmanConstants.DV_VER + TrafficmanConstants.CURRENT_JV_FILE_ID + ".sqlite";
        } else {
            TrafficmanConstants.DATABASE_NAME = "default" + TrafficmanConstants.DV_VER + TrafficmanConstants.CURRENT_JV_FILE_ID + ".sqlite";
        }

        mainMenu_Database_Create();

        TrafficmanConstants.SAVE_CLICK = 1;
        setResult(RESULT_OK);

//		Intent intent = new Intent(this, Trafficman_Projects_Notepad.class);
//		startSubActivity(intent, ACTIVITY_CREATE);
        finish();
    }

    private void set_Current_JV_file(long id) {

        TrafficmanFilesNotesDbAdapter selected_JV_File_mDbHelper = new TrafficmanFilesNotesDbAdapter(
                this);
        selected_JV_File_mDbHelper.open();

        // set all records off
        Cursor selected_JV_File_Cursor = selected_JV_File_mDbHelper.fetchAllNotes();
        startManagingCursor(selected_JV_File_Cursor);
        int record_count = selected_JV_File_Cursor.count();
        if (record_count > 0) {
            selected_JV_File_Cursor.first();
            int columnID = selected_JV_File_Cursor.getColumnIndex("jv_selected_file_id");
            for (int i = 0; i < record_count; ++i) {
                selected_JV_File_Cursor.updateInt(columnID, 0);
                selected_JV_File_Cursor.commitUpdates();

                selected_JV_File_Cursor.next();
            }
        }

        // set selected record as selected file
        Cursor update_JV_File_Cursor = selected_JV_File_mDbHelper.fetchNote(id);
        startManagingCursor(update_JV_File_Cursor);
        int record_count2 = update_JV_File_Cursor.count();
        if (record_count2 > 0) {
            update_JV_File_Cursor.first();
            int columnID = update_JV_File_Cursor.getColumnIndex("jv_selected_file_id");
            update_JV_File_Cursor.updateInt(columnID, 1);
            update_JV_File_Cursor.commitUpdates();
        }

        selected_JV_File_mDbHelper.close();
    }

    private void get_Current_JV_file() {

        TrafficmanFilesNotesDbAdapter current_JV_File_mDbHelper = new TrafficmanFilesNotesDbAdapter(
                this);
        current_JV_File_mDbHelper.open();

        Cursor current_JV_File_Cursor = current_JV_File_mDbHelper.fetchAllNotes();
        startManagingCursor(current_JV_File_Cursor);
        int record_count = current_JV_File_Cursor.count();
        int columnID = current_JV_File_Cursor.getColumnIndex("_id");
        int columnID2 = current_JV_File_Cursor.getColumnIndex("jv_title");
        int columnID3 = current_JV_File_Cursor.getColumnIndex("jv_selected_file_id");
        if (record_count > 0) {
            current_JV_File_Cursor.first();
            for (int i = 0; i < record_count; ++i) {
                int_selected_id = current_JV_File_Cursor.getInt(columnID3);
                if (int_selected_id == 1) {
                    // we have a winner
                    long lng_rowID = current_JV_File_Cursor.getLong(columnID);
                    TrafficmanConstants.CURRENT_JV_FILE_ID = lng_rowID;
                    TrafficmanConstants.CURRENT_JV_FILE_TITLE = current_JV_File_Cursor.getString(columnID2);
                }
                current_JV_File_Cursor.next();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            String data, Bundle extras) {
        super.onActivityResult(requestCode, resultCode, data, extras);
        fillData();
    }

    public class ImageAdapter extends BaseAdapter {

        private Integer[] mThumbIds = {R.drawable.projects_001,
            R.drawable.tasks_003, R.drawable.schedule_01,
            R.drawable.bidding_001, R.drawable.contacts_01
        };

        public ImageAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mThumbIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView i = new ImageView(mContext);

            i.setImageResource(mThumbIds[position]);
            i.setAdjustViewBounds(true);
            i.setLayoutParams(new Gallery.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            i.setBackground(android.R.drawable.picture_frame);
            return i;
        }
        private Context mContext;
    }

    @Override
    protected void onPause() {
        if (int_intent_active == 1) {
            // do nothing
            int_intent_active = 0;
            super.onPause();
        } else {
            super.onPause();
            // Intent intent = new Intent();
            // intent.setClass(Trafficman_Files_Notepad.this,
            // Trafficman_Files_Notepad.class);
            // startActivity(intent);
            finish();
        }

    }

    @Override
    protected void onResume() {
        if (int_intent_active == 0) {
            super.onResume();
            fillData();
        }
    }

    public void mainMenu_Database_Create() {

        if (TrafficmanConstants.ACTIVE_DEVICE.equals("sdcard")) {
            // create a trafficman file on sdcard
            db = SQLiteDatabase.open(TrafficmanConstants.DATABASE_NAME, null);
            if (db == null) {
                db = SQLiteDatabase.create(TrafficmanConstants.DATABASE_NAME,
                        TrafficmanConstants.DATABASE_VERSION, null);
                db.execSQL("create table if not exists contacts" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, contact_id integer, contact_role_id integer, name text not null, company text not null, jobtitle text not null, mobile_phone text not null, home_phone text not null, work_phone text not null, email text not null, emailwork text not null, homeaddress text not null, workaddress text not null, notes text not null, future1 text not null, future2 text not null, future3 text not null, datetime_record_created text not null, datetime_record_updated text not null)");
                db.execSQL("create table if not exists roles" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, integer role_id, role text not null, datetime_record_created text not null, datetime_record_updated text not null);");
                db.execSQL("create table if not exists bidding" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, bid_id integer, bid_amount text not null, bidder_contact_id integer, jobtask_id integer, selected_id integer, bid_title text not null, bid_proposal text not null, datetime_record_created text not null, datetime_record_updated text not null)");
                db.execSQL("create table if not exists jobtask" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, jobtask_id integer, role_id integer, project_id integer, current_id integer, selected_bid_id integer, bid_estimate numeric, bid_actual numeric, schedule_id integer, completed_id integer, jobtask_title text not null, specification text not null, datetime_record_created text not null, datetime_record_updated text not null)");
                db.execSQL("create table if not exists schedule" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, schedule_id integer, project_id integer, jobtask_id integer, schedule_name text not null, schedule_information text not null, schedule_start text not null, schedule_end text not null, selected_id integer, datetime_record_created text not null, datetime_record_updated text not null)");
                db.execSQL("CREATE TABLE IF NOT EXISTS projects" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, project_id integer, project_type_id integer, project_contact_id integer, project_name text not null, project_description text not null, datetime_record_created text not null, datetime_record_updated text not null)");
                db.execSQL("create table if not exists project_types" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, prj_type text not null, datetime_record_created text not null, datetime_record_updated text not null);");
            }

        } else {
            // create a trafficman file on device
            try {
                db = openDatabase(TrafficmanConstants.DATABASE_NAME, null);
            } catch (FileNotFoundException e) {
                try {
                    db = createDatabase(TrafficmanConstants.DATABASE_NAME,
                            TrafficmanConstants.DATABASE_VERSION, 0, null);
                    db.execSQL("create table if not exists contacts" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, contact_id integer, contact_role_id integer, name text not null, company text not null, jobtitle text not null, mobile_phone text not null, home_phone text not null, work_phone text not null, email text not null, emailwork text not null, homeaddress text not null, workaddress text not null, notes text not null, future1 text not null, future2 text not null, future3 text not null, datetime_record_created text not null, datetime_record_updated text not null)");
                    db.execSQL("create table if not exists roles" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, integer role_id, role text not null, datetime_record_created text not null, datetime_record_updated text not null);");
                    db.execSQL("create table if not exists bidding" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, bid_id integer, bid_amount text not null, bidder_contact_id integer, jobtask_id integer, selected_id integer, bid_title text not null, bid_proposal text not null, datetime_record_created text not null, datetime_record_updated text not null)");
                    db.execSQL("create table if not exists jobtask" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, jobtask_id integer, role_id integer, project_id integer, current_id integer, selected_bid_id integer, bid_estimate numeric, bid_actual numeric, schedule_id integer, completed_id integer, jobtask_title text not null, specification text not null, datetime_record_created text not null, datetime_record_updated text not null)");
                    db.execSQL("create table if not exists schedule" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, schedule_id integer, project_id integer, jobtask_id integer, schedule_name text not null, schedule_information text not null, schedule_start text not null, schedule_end text not null, selected_id integer, datetime_record_created text not null, datetime_record_updated text not null)");
                    db.execSQL("CREATE TABLE IF NOT EXISTS projects" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, project_id integer, project_type_id integer, project_contact_id integer, project_name text not null, project_description text not null, datetime_record_created text not null, datetime_record_updated text not null)");
                    db.execSQL("create table if not exists project_types" + TrafficmanConstants.DV_VER + " (_id integer primary key autoincrement, prj_type text not null, datetime_record_created text not null, datetime_record_updated text not null);");

                } catch (FileNotFoundException e1) {
                    db = null;
                }
            }
        }
    }

    private void TrafficmanInitialize() {

        TrafficmanConstants.PROJECT_SET_PROJECT_ROWID = Long.valueOf(0);
        TrafficmanConstants.SCHEDULE_SET_PROJECT_ROWID = Long.valueOf(0);
        TrafficmanConstants.SCHEDULE_SET_SCHEDULE_ROWID = Long.valueOf(0);
        TrafficmanConstants.JOBTASK_ROWID = Long.valueOf(0);

        TrafficmanConstants.SCHEDULE_SET_PROJECT = 0;
        TrafficmanConstants.JOBTASK_SET_SCHEDULE = 0;
        TrafficmanConstants.JOBTASK_SET_PROJECT = 0;
        TrafficmanConstants.JV_SELECTED_FILE_ID = 0;

        TrafficmanFilesLocationNotesDbAdapter active_device_mDbHelper = new TrafficmanFilesLocationNotesDbAdapter(
                this);
        active_device_mDbHelper.open();
        active_device_mDbHelper.fetch_Active_Storage_Location();
        active_device_mDbHelper.close();
    }

    private void Load_Sample_Data() {
        try {
            InputStream in = getAssets().open("example_db");
            String outFilename = "/data/data/com.meridianhouseplans.trafficman2/databases/default47";
            OutputStream out = new FileOutputStream(outFilename);

            // Transfer bytes from in_file to out_file
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            // Close the streams
            out.close();
            in.close();
        } catch (IOException e) {
        }

    // AlertDialog.show(this, "Trafficman2 Example Data", 1, "Import
    // Completed",
    // "OK", false);
    }
}
